<?php

namespace app\admin\framework\controller;

use app\admin\framework\api\Permission;
use app\common\model\AdminMenu;
use Shopwwi\LaravelCache\Cache;
use think\facade\Db;


#[Permission('菜单管理', 'System')]
class MenuController
{
    public $noNeedLogin = ['refresh'];
    
    #[Permission('详情')]
    public function detail()
    {
        $id = request()->get('id', 0);
        $result = AdminMenu::find($id)->toArray();
        return apiSuccess(data: $result);
    }
    
    #[Permission('查询')]
    public function select()
    {
        $result = AdminMenu::order('list_order asc')->select()->toArray();
        return apiSuccess(data: ['list' => $result]);
    }
    
    #[Permission('创建')]
    public function create()
    {
        if (request()->method() === 'PUT') {
            $data = request()->post();
            (new AdminMenu())->save($data);
            return apiSuccess('保存成功');
        }
        return apiError('保存失败');
    }
    
    
    #[Permission('更新')]
    public function update()
    {
        if (request()->method() === 'PUT') {
            $data = request()->post();
            (new AdminMenu())->update($data);
            return apiSuccess('保存成功');
        }
        return apiError('保存失败');
    }
    
    #[Permission('删除')]
    public function delete()
    {
        if (request()->method() === 'DELETE') {
            $id = request()->get('id', 0);
            $count = AdminMenu::where("parent_id", $id)->count();
            if ($count > 0) {
                return apiError('该菜单下还有子菜单，无法删除！');
            }
            if (AdminMenu::destroy($id) !== false) {
                return apiSuccess('删除成功');
            } else {
                return apiError('删除失败');
            }
        }
        return apiError('删除失败');
    }
    
    
    #[Permission('一键更新')]
    public function refresh()
    {
        $phpFiles = glob(app_path() . '/admin/*/controller/*.php');
        
        
        $menus = [];
        $permissions = [];
        foreach ($phpFiles as $file) {
            $controller = basename($file, '.php');
            preg_match('/(\/app\/admin\/(.*)\/controller\/)/', $file, $matches);
            $namespace = str_replace('/', '\\', $matches[1]);
            $dir = $matches[2];
            $reflectionClass = new \ReflectionClass($namespace . $controller);
            $attributes = $reflectionClass->getAttributes(Permission::class);
            if (!empty($attributes)) {
                $menu = $attributes[0]->newInstance()?->menu;
                $controller = str_replace('Controller', '', $controller);
                $menus[$menu['parent']][] = [
                    'title' => $menu['title'],
                    'type' => 2,
                    'name' => $controller,
                    'list_order' => $menu['list_order'],
                    'key' => $namespace . $controller,
                    'dir' => $dir
                ];
            }
            
            foreach ($reflectionClass->getMethods() as $method) {
                if ($method->getDeclaringClass()->getName() === $reflectionClass->getName()) {
                    $methodAttribute = $method->getAttributes(Permission::class);
                    if (!empty($methodAttribute)) {
                        $controller = str_replace('Controller', '', $controller);
                        $permission = $methodAttribute[0]->newInstance()?->menu;
                        if (!empty($permission['parent'])) {
                            // 代表直接继承于顶级菜单
                            $menus[$permission['parent']][] = [
                                'title' => $permission['title'],
                                'type' => 2,
                                'name' => $method->getName(),
                                'key' => $namespace . $controller . '@' . $method->getName(),
                                'dir' => $dir,
                                'list_order' => $permission['list_order'],
                            ];
                        } else {
                            $permissions[$menu['parent'] . '.' . $controller][] = [
                                'title' => $permission['title'],
                                'type' => 3,
                                'name' => $method->getName(),
                                'key' => $namespace . $controller . '@' . $method->getName(),
                                'dir' => $dir,
                                'list_order' => $permission['list_order'],
                            ];
                        }
                    }
                }
            }
        }
        
        
        Db::startTrans();
        try {
            $adminMenuModel = new AdminMenu();
            // 删除所有的菜单
            $adminMenuModel->where(1, 1)->delete();
            // 1.目录
            foreach (Permission::TOP as $value) {
                $dirId = $adminMenuModel->insertGetId([
                    'type' => 1,
                    'name' => $value['name'],
                    'title' => $value['title'],
                    'path' => '/' . $value['name'],
                    'list_order' => $value['list_order']
                ]);
                if (!empty($menus[$value['name']])) {
                    foreach ($menus[$value['name']] as $v2) {
                        $menuId = $adminMenuModel->insertGetId([
                            'type' => 2,
                            'path' => '/' . $v2['dir'] . '/' . $v2['name'],
                            'name' => $v2['name'],
                            'title' => $v2['title'],
                            'parent_id' => $dirId,
                            'key' => $v2['key'],
                            'list_order' => $v2['list_order']
                        ]);
                        if (!empty($permissions[$value['name'] . '.' . $v2['name']])) {
                            foreach ($permissions[$value['name'] . '.' . $v2['name']] as $v3) {
                                $adminMenuModel->insertGetId([
                                    'type' => 3,
                                    'name' => $v3['name'],
                                    'title' => $v3['title'],
                                    'parent_id' => $menuId,
                                    'path' => '/' . $v2['dir'] . '/' . $v2['name'] . '@' . $v3['name'],
                                    'status' => 0,
                                    'key' => $v3['key']
                                ]);
                            }
                        }
                    }
                }
            }
            Cache::forget('em_admin_menu');
            Db::commit();
            
        } catch (\Exception $e) {
            Db::rollBack();
            return apiError($e->getMessage() . ':' . $e->getLine() . '行');
        }
        return apiSuccess('更新成功!');
    }
    
    
}